package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.pojo.Video;
import com.service.VideoService;
import com.util.CapturePictureFromVideo;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/video")
public class VideoController {
    private final String videopath="D:\\java\\video\\";
    private final String picturepath="D:\\java\\picture\\";
    @Resource(name="video")
    private VideoService videoService;
    private String filetype;
    @RequestMapping(value="/upload")
    public void upload(HttpServletRequest request,MultipartFile file,HttpServletResponse response)  {
        this.DirectoryIsExisted(videopath);
        this.DirectoryIsExisted(picturepath);
        if (IsType(file.getOriginalFilename())&&IsSize(file)){
            boolean result=UploadVideo(file);
            ReturnResult(response,result);
            if (result){
                System.out.println(videopath+file.getOriginalFilename());
                System.out.println(picturepath+getVideoName(file.getOriginalFilename())+".jpg");
                new CapturePictureFromVideo(videopath+file.getOriginalFilename(),picturepath+getVideoName(file.getOriginalFilename())+".jpg").start();
                Video video=CreateVideo(file,request);
                videoService.UploadVideo(video);
            }
        }
        else
            ReturnResult(response,false);
    }
    @RequestMapping(value="/playvideo")
    public void playvideo(HttpServletRequest request,HttpServletResponse response){
        try {
            System.out.println(request.getParameter("key"));
            Integer id=Integer.parseInt(request.getParameter("key"));
            List<Video> videos=videoService.selectUserVideo(id);
            System.out.println(id);
            ReturnOne(response,videos);
        }catch (Exception e){
            e.printStackTrace();
            ReturnAll(response);
        }
    }
    private void DirectoryIsExisted(String path){
        File file=new File(path);
        if(file.exists())
            return;
        else
            file.mkdir();
    }
    private boolean IsType(String FileUrl){
        String[] VideoMessage=FileUrl.split("\\.");
        String type=VideoMessage[VideoMessage.length-1];
        //System.out.println(type);
        if(type.equals("mp4"))
            return true;
        else
            return false;
    }
    private String getVideoName(String FileUrl){
        String[] VideoMessage=FileUrl.split("\\.");
        return VideoMessage[0];
    }
    private boolean IsSize(MultipartFile file){
        if(file.getSize()/1024<30*1024)
            return true;
        else
            return false;
    }
    private boolean UploadVideo(MultipartFile file){
        try {
            String FileUrl=file.getOriginalFilename();
            Streams.copy(file.getInputStream(),new FileOutputStream(videopath+FileUrl),
                    true);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    private Video CreateVideo(MultipartFile file,HttpServletRequest request){
        Video video=new Video();
        video.setId(videoService.selectMaxId()+1);
        video.setCategoryid(1);
        video.setUserid(1);
        video.setTittle(file.getOriginalFilename());
        video.setFlag(1);
        return video;
    }
    private void ReturnResult(HttpServletResponse response, boolean result){
        try {
            PrintWriter writer=response.getWriter();
            JSONObject jsonObject=new JSONObject();
            if(result)
                jsonObject.put("code",1);
            else
                jsonObject.put("code",0);
            response.setContentType("text/html;charset=UTF-8");
            writer.print(jsonObject);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void ReturnAll(HttpServletResponse response){
        try {
            ArrayList<String> videosrc=new ArrayList<>();
            ArrayList<String> picturesrc=new ArrayList<>();
            ArrayList<String> videoname=new ArrayList<>();
            PrintWriter writer=response.getWriter();
            JSONObject jsonObject=new JSONObject();
            File videodirectory=new File(videopath);
            File[] videos=videodirectory.listFiles();
            for(File temp:videos){
                String video="/video/"+temp.getName();
                System.out.println(video);
                videosrc.add(video);
                String[] temps=temp.getName().split("\\.");
                videoname.add(temps[0]);
            }
            File picturedirectory=new File(picturepath);
            File[] pictures=picturedirectory.listFiles();
            for(File temp:pictures){
                String picture="/image/"+temp.getName();
                System.out.println(picture);
                picturesrc.add(picture);
            }
            jsonObject.put("picturesrc",picturesrc);
            jsonObject.put("videosrc",videosrc);
            jsonObject.put("videoname",videoname);
            response.setContentType("text/html;charset=UTF-8");
            writer.print(jsonObject);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void ReturnOne(HttpServletResponse response,List<Video> video){
        try {
            ArrayList<String> videosrc=new ArrayList<>();
            ArrayList<String> picturesrc=new ArrayList<>();
            ArrayList<String> videoname=new ArrayList<>();
            PrintWriter writer=response.getWriter();
            JSONObject jsonObject=new JSONObject();
            File videodirectory=new File(videopath);
            File[] videos=videodirectory.listFiles();
            for(File temp:videos){
                System.out.println("RESULT："+video.size());
                for(Video temp1:video){
                    String picture="/image/"+temp.getName();
                    String videostr="/video/"+temp.getName();
                    String[] temps=temp.getName().split("\\.");
                    if(temp.getName().equals(temp1.getTittle())){
                        videosrc.add(videostr);
                        videoname.add(temps[0]);
                        picturesrc.add(picture);
                    }
                }
            }
            jsonObject.put("picturesrc",picturesrc);
            jsonObject.put("videosrc",videosrc);
            jsonObject.put("videoname",videoname);
            response.setContentType("text/html;charset=UTF-8");
            writer.print(jsonObject);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
